import React, {useEffect, useRef, useState} from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { connect} from 'umi';
import {
  getCertificateList,
  saveOrUpdateCertificateInfo,
  deleteProver,
  getContractModelList, getContractSubjectList,memberCertificateBpm
} from './service';
import {Popconfirm,Divider,Button,message} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import AddForm from './components/AddForm';
import store from 'store2';
import { BPMStatusEnum } from '@/utils/constant'

const TableList = ({currentUser}) => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(false);
  const [loading,setLoading] = useState(false);
  const [record,setRecord] = useState(null);
  const [contractList,setContractList] = useState([]);
  const [contractData, setContractData] = useState([]);

  useEffect(() => {
    getContractModelList().then(res => {
      setContractList(res.filter((item) => item.name !== "收入证明-已离职人员模板"));
    });
    //获取合同主体
    getContractSubjectList().then(res => {
      setContractData(res);
    });
  }, []);

  const confirmDelete = (id) => {
    deleteProver(id).then(res => {
      if(res.flag){
        message.success('删除成功！');
        actionRef.current.reload();
      }else{
        message.error(res.error);
      }
    });
  };

  const addOrEditProve = (record) => {
    if(record){
      setRecord(record);
    }
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    setRecord(null);
  };

  const confirmInitiate = (id) => {
    memberCertificateBpm(id).then(res => {
      if(res.flag){
        message.success('操作成功！');
        window.open(res.data);
        actionRef.current.reload();
      }else{
        message.error(`bpm错误:` + res.error);
      }
    });
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveOrUpdateCertificateInfo(values).then((res) => {
      if (res.flag) {
        handleCancel();
        store.remove(`personnel-prove-` + currentUser.id);
        message.success('申请发送成功！');
        actionRef.current.reload();
      } else {
        message.error(`操作失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const columns = [
    {
      title: '序号',
      render:(text,record,index)=>`${index+1}`,
      hideInSearch: true,
    },
    {
      title: '工号',
      dataIndex: 'code'
    },
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '公司',
      dataIndex: 'orgName',
    },
    {
      title: '部门',
      dataIndex: 'unitName',
    },
    {
      title: '岗位',
      dataIndex: 'jobName',
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '证明类型',
      dataIndex: 'modelId',
      render: (text) => {
        return  contractList.find((item) => item.id === text).name
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: BPMStatusEnum
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      width: '15%',
      render: (item, record) => (
        <>
          {(record.status === '0') && <>
            <a onClick={() => addOrEditProve(record)}>修改</a>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => confirmDelete(record.id)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认发起?`} onConfirm={() => confirmInitiate(record.id)} okText="是" cancelText="否">
              <a>发起</a>
            </Popconfirm>
          </>}
          {(record.status === '1') && <><a onClick={() => window.open(record.bpmUrl)}>审批详情</a></>}
          {(record.status === '2' && record.contractOssUrl) && <><a onClick={() => window.open(record.contractOssUrl)}>下载证明</a></>}
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable
        search={false}
        actionRef={actionRef}
        rowKey="id"
        request={(params) => getCertificateList(params)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => addOrEditProve(null)}><PlusOutlined/>新增</Button>
        ]}
      />
      <AddForm
        loading={loading}
        visible={visible}
        record={record}
        contractList={contractList}
        contractData={contractData}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser
}))(TableList)
